package com.jaryle.wenxin.controller;


import com.alibaba.fastjson.JSONObject;
import com.jaryle.wenxin.bean.message.ImageMessage;
import com.jaryle.wenxin.bean.message.TextMessage;
import com.jaryle.wenxin.util.menu.MenuUtil;
import com.jaryle.wenxin.util.message.ImageMessageUtil;
import com.jaryle.wenxin.util.message.MessageUtil;
import com.jaryle.wenxin.util.WeiXinUtil;
import com.jaryle.wenxin.util.message.TextMessageUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;


/**
 * 描述:
 * 微信公众号开发
 *
 * @author jaryle
 * @version V1.0
 * @date 2018-11-26
 */
@Controller
@RequestMapping(value = "/wechat")
public class WeiXinController {

//    @Autowired
//    private SchedulerJobService schedulerJobService;
    private static final String tocken = "hellojaryle";
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 测试页面
     */
    @GetMapping("/hello")
    public String hello(ModelMap model){
        model.addAttribute("host","www.jaryle.top");
        return "hello";
    }



    /**
     * 验证微信后台配置的服务器地址有效性
     * 接收并校验四个请求参数
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return echostr
     * @author jaryle
     * @date 2018-12-24
     */
    @GetMapping("/checkSignature")
    @ResponseBody
    public static String checkSignature(@RequestParam(name = "nonce") String nonce, @RequestParam(name = "timestamp") String timestamp, @RequestParam(name = "echostr") String echostr, @RequestParam(name = "signature") String signature) {
        System.out.println("微信-开始校验签名");
        System.out.println("收到来自微信的 echostr 字符串:{}"+echostr);

        // 加密/校验流程如下:
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        // 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        // 1.排序
        String sortString = WeiXinUtil.sort(tocken, timestamp, nonce);
        // 2.sha1加密
        String myString = WeiXinUtil.sha1(sortString);
        // 3.字符串校验
        if (myString != null && myString != "" && myString.equals(signature)) {
            System.out.println("微信-签名校验通过");
            //如果检验成功原样返回echostr，微信服务器接收到此输出，才会确认检验完成。
            System.out.println("回复给微信的 echostr 字符串:{}"+echostr);
            return echostr;
        } else {
            System.out.println("微信-签名校验失败");
            return "";
        }
    }


    /**
     * 消息管理，微信服务器以xml形式发送信息到服务器
     * post请求
     * @author jaryle
     * @date 2018-12-24
     */
    @PostMapping("/sendmessage")
    @ResponseBody
    public void sendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String message = "";
        //将request请求，传到Message工具类的转换方法中，返回接收到的Map对象
        Map<String, String> map = MessageUtil.xmlToMap(request);
        //从集合中，获取XML各个节点的内容
        String ToUserName = map.get("ToUserName");
        String FromUserName = map.get("FromUserName");
        String CreateTime = map.get("CreateTime");
        String MsgType = map.get("MsgType");
        String MsgId = map.get("MsgId");
        if ("text".equals(MsgType)) {
            TextMessageUtil textMessageUtil =new TextMessageUtil();
            TextMessage textMessage = new TextMessage();
            textMessage.setContent(map.get("Content"));
            message = textMessageUtil.initMessage(FromUserName,ToUserName,textMessage);
        }else if("image".equals(MsgType)){
            ImageMessageUtil imageMessageUtil = new ImageMessageUtil();
            ImageMessage imageMessage = new ImageMessage();
            imageMessage.getImage().setPicUrl(map.get("PicUrl"));
            message = imageMessageUtil.initMessage(FromUserName,ToUserName,imageMessage);
        }
        try {
            out.write(message);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
        }

    }
    /**
     * 创建菜单
     */
    public void creatMenu(){
        //获取access_token
        String accessToken = WeiXinUtil.getAccess_Token();
        //初始化菜单
        String menu = MenuUtil.initMenu();
        //创建菜单
        JSONObject menuJson = MenuUtil.createMenu(accessToken, menu);
        if("0".equals(menuJson.getString("errcode"))){
            System.out.println("创建菜单成功！");
        }else{
            System.out.println(menuJson.getString("errmsg"));
        }
    }

}
